/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gl.tp1;

/**
 *
 * @author wadi3
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class ClientBasePS {

    public Utilisateur loadUser(String login, String pass) {
        Connection conn = UtilitaireConnection.getConnection();
        Utilisateur u = null;
        try {
            PreparedStatement ps = conn.prepareStatement("select * from ROOT.\"UTILISATEURS\" where login=? and pass=?");
            ps.setString(1, login);
            ps.setString(2, pass);
            ResultSet rsUser = ps.executeQuery();
            if (rsUser.next()) {
                u = new Utilisateur();
                u.setIdUser(new Integer(rsUser.getInt("ID_USER")));
                u.setLogin(rsUser.getString("LOGIN"));
                u.setPass(rsUser.getString("PASS"));
                u.setEmail(rsUser.getString("EMAIL"));
                u.setVille(rsUser.getString("VILLE"));
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return u;
    }

    public void addUser(String l, String p, String e, String v) {
        Connection conn = UtilitaireConnection.getConnection();
        Utilisateur u = null;
        try {
            PreparedStatement ps = conn.prepareStatement("insert into ROOT.\"UTILISATEURS\"(LOGIN,PASS,EMAIL,VILLE) values(?,?,?,?)");
            ps.setString(1, l);
            ps.setString(2, p);
            ps.setString(3, e);
            ps.setString(4, v);
            ps.executeUpdate();
        } catch (SQLException e2) {
            e2.printStackTrace();
        }
    }

    public Vector selectAll() {
        Connection conn = UtilitaireConnection.getConnection();
        Vector<Utilisateur> users = new Vector();
        Utilisateur u = null;
        try {
            PreparedStatement ps = conn.prepareStatement("select * from ROOT.\"UTILISATEURS\"");
            ResultSet rsUser = ps.executeQuery();
            while (rsUser.next()) {
                u = new Utilisateur();
                u.setIdUser(new Integer(rsUser.getInt("ID_USER")));
                u.setLogin(rsUser.getString("LOGIN"));
                u.setPass(rsUser.getString("PASS"));
                u.setEmail(rsUser.getString("EMAIL"));
                u.setVille(rsUser.getString("VILLE"));
                users.add(u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    public static void main(String[] args) {
        ClientBasePS cbs = new ClientBasePS();
        cbs.addUser("a", "b", "c", "d");
        Vector<Utilisateur> v = cbs.selectAll();
        for (int i = 0; i < v.size(); i++) {
            System.out.println(v.elementAt(i));
        }
    }
}